

package search.fitnessfunctions;


import java.util.*;
import java.util.logging.*;
import primitives.cluster.*;

public class MedianLevelMQ extends BunchTurboMQFitnessFunction{
	
	public double evaluate(ClusterHead ch){
		
		
		int depth = LayeringMQ.maxDepth(ch);
		
		ClusterHead toEval = LayeringMQ.extendLayers(ch,depth);
		
		int level = 0;
		int median = (depth-1)/2;
		
		int target = (depth-1) - median;
		
		
//		Logger.getLogger("errors").log(Level.SEVERE,String.format("Target :%d from median %d and depth %d",target,median,depth));

		
		double total = 0;
		
		HashSet<IClusterLevel> current = new HashSet<IClusterLevel>();
		current.add(ch);
		
		
		int count = current.size();
		while(!current.isEmpty() && count > 0){
			HashSet<IClusterLevel> next = new HashSet<IClusterLevel>();
			ClusterHead temp = new ClusterHead(current, true);
			
			double fitness=0;
			
			count = 0;
			if(target == 0){
				return super.evaluate(temp);
			}
			target--;
//			Logger.getLogger("traces").Log(Level.INFO,"target="+target);
			total += fitness;
			
			
			for(IClusterLevel c: current){
				
				for(IClusterLevel d: ((ClusterNode)c).getChildren()){
					if(d.encapsulates()){
						
						next.add(d);
						if( ((ClusterNode)d).getNodes().size() > 1){
							count++;
						}
					}
				}
			}
			
			current = next;
		}
		
		Logger.getLogger("errors").log(Level.SEVERE,"Error! Median MQ FF didn't evaluate median. Target is still " + target);
		return 0;
	}



}